﻿using System.Security.Principal;
using System.Web;
using System.Web.Security;

namespace IrisMembership.Web.Authentication
{
    public class IrisSupportPrincipalService : IPrincipalService
    {
        private readonly HttpContextBase _context;

        public IrisSupportPrincipalService(HttpContextBase context)
        {
            _context = context;
        }

        #region IPrincipalService Members

        public IPrincipal GetCurrent()
        {
            var user = _context.User;

            // if they are already signed in, and conversion has happened
            if (user is IrisPrincipal)
                return user;

            // if they are signed in, but conversion has still not happened
            if (user == null || !user.Identity.IsAuthenticated || !(user.Identity is FormsIdentity))
                return new IrisPrincipal(new IrisIdentity((FormsAuthenticationTicket)null));

            var identity = (FormsIdentity)_context.User.Identity;

            var ticket = identity.Ticket;

            if (FormsAuthentication.SlidingExpiration)
                ticket = FormsAuthentication.RenewTicketIfOld(ticket);

            var irisIdentity = new IrisIdentity(ticket);

            return new IrisPrincipal(irisIdentity);
        }

        #endregion
    }
}